package com.framework.web;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.alibaba.fastjson.JSONObject;
import com.common.model.StaffInfoModel;
import com.common.utils.ServerInfo;
import com.common.utils.SysConfig;


public abstract class BaseController {
	protected static Log log = LogFactory.getLog(BaseController.class);
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private ResourceBundleMessageSource _res;
	

	public StaffInfoModel getSessionUserInfo(){
		return  (StaffInfoModel)request.getSession().getAttribute(SysConfig.ATTRIBUTE_USER_KEY);
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		
	}

	protected ModelAndView ajaxDone(int statusCode, String message, String forwardUrl) {
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", statusCode);
		mav.addObject("message", message);
		mav.addObject("forwardUrl", forwardUrl);
		return mav;
	}
	
	protected ModelAndView ajaxDoneSuccess(String message) {
		return ajaxDone(200, message, "");
	}

	protected ModelAndView ajaxDoneError(String message) {
		return ajaxDone(300, message, "");
	}
	protected String getMessage(String code) {
		return this.getMessage(code, new Object[] {});
	}

	protected String getMessage(String code, Object arg0) {
		return getMessage(code, new Object[] { arg0 });
	}

	protected String getMessage(String code, Object arg0, Object arg1) {
		return getMessage(code, new Object[] { arg0, arg1 });
	}

	protected String getMessage(String code, Object arg0, Object arg1,
			Object arg2) {
		return getMessage(code, new Object[] { arg0, arg1, arg2 });
	}

	protected String getMessage(String code, Object arg0, Object arg1,
			Object arg2, Object arg3) {
		return getMessage(code, new Object[] { arg0, arg1, arg2, arg3 });
	}

	protected String getMessage(String code, Object[] args) {
		//HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		Locale locale = localeResolver.resolveLocale(request);

		return _res.getMessage(code, args, locale);
	}
	
	protected boolean verifyValidationCode(
			String validationCode) {

	
		return true;
	}
	
	@ExceptionHandler(Exception.class)
	public ModelAndView exception(Exception e, HttpServletRequest request) {
		e.printStackTrace();
		log.info("exception");
		request.setAttribute("exception", e);
		
		if (ServerInfo.isAjax(request) || request.getParameter("ajax") != null) {
			return ajaxDoneError(e.getMessage());
		}
		
		ModelAndView mav = new ModelAndView("error");
		mav.addObject("statusCode", 300);
		mav.addObject("message", e.getMessage());
		
		return mav;
	}
	
	/**
	 * 根据字符串输出JSON，返回null
	 * 
	 * @param jsonString
	 * @return
	 */
	public static String ajaxJson(HttpServletResponse response,String jsonString) {
		return ajax(response,jsonString, "text/html");
	}
	
	/**
	 * AJAX输出，返回null
	 * 
	 * @param content
	 * @param type
	 * @return
	 */
	public static String ajax(HttpServletResponse response, String content, String type) {
		try {
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			log.error("IOException:", e);
		}
		return null;
	}
	
	
	public String jsonReturn(HttpServletResponse response,int statusCode) {
		JSONObject jsonString = new JSONObject();
		//HashMap jsonObj1 = new HashMap<String, Object>();
		if(statusCode == 200) {
			jsonString.put("statusCode", "200");
			jsonString.put("message", "操作成功");
		} else if (statusCode == 300) {
			jsonString.put("statusCode", "300");
			jsonString.put("message", "操作失败，请重试");
		}
		jsonString.put("closeCurrent", true);
		return ajax(response,jsonString.toJSONString(), "text/html");
	}
	
	
	
	public String jsonReturn(HttpServletResponse response,int statusCode,boolean closeCurrent) {
		JSONObject jsonString = new JSONObject();
		//HashMap jsonObj1 = new HashMap<String, Object>();
		if(statusCode == 200) {
			jsonString.put("statusCode", "200");
			jsonString.put("message", "操作成功");
		} else if (statusCode == 300) {
			jsonString.put("statusCode", "300");
			jsonString.put("message", "操作失败，请重试");
		}
		jsonString.put("closeCurrent", closeCurrent);
		return ajax(response,jsonString.toJSONString(), "text/html");
	}
	
	
	public String jsonReturn(HttpServletResponse response,int statusCode,String message) {
		JSONObject jsonString = new JSONObject();
		//HashMap jsonObj1 = new HashMap<String, Object>();
		if(statusCode == 200) {
			jsonString.put("statusCode", "200");
			jsonString.put("message", message);
		} else if (statusCode == 300) {
			jsonString.put("statusCode", "300");
			jsonString.put("message", message);
		}
		jsonString.put("closeCurrent", true);
		return ajax(response,jsonString.toJSONString(), "text/html");
	}
	
	public String jsonReturn(HttpServletResponse response,int statusCode,String message,boolean closeCurrent) {
		JSONObject jsonString = new JSONObject();
		//HashMap jsonObj1 = new HashMap<String, Object>();
		if(statusCode == 200) {
			jsonString.put("statusCode", "200");
			jsonString.put("message", message);
		} else if (statusCode == 300) {
			jsonString.put("statusCode", "300");
			jsonString.put("message", message);
		}
		jsonString.put("closeCurrent", closeCurrent);
		return ajax(response,jsonString.toJSONString(), "text/html");
	}

	public StaffInfoModel getUserSession(HttpServletRequest request2) {
		return (StaffInfoModel)request.getSession().getAttribute(SysConfig.ATTRIBUTE_USER_KEY);
	}
}
